package com.infonam.media.activities;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore.Video.Thumbnails;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.VideoView;

import com.infonam.media.R;
import com.infonam.media.adapters.VideoAdapter;
import com.infonam.media.data.VideoInfo;

public class ListVideoActivity extends Activity {

	private ListView listview;

	private List<VideoInfo> listvideoinfo = new LinkedList<VideoInfo>();
	private static ProgressDialog progressDialog;
	String videourl;
	private MyTask objMyTask;
	VideoView videoView;

	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.listvideoview);

		progressDialog = ProgressDialog.show(ListVideoActivity.this, "",
				"Buffering video...", true);
		progressDialog.setCancelable(true);
		objMyTask = new MyTask();
		objMyTask.execute();

	}

	private void PlayVideo(String videoPath) {
		try {
			getWindow().setFormat(PixelFormat.TRANSLUCENT);
			MediaController mediaController = new MediaController(
					ListVideoActivity.this);
			mediaController.setAnchorView(videoView);

			Uri video = Uri.parse(videoPath);
			videoView.setMediaController(mediaController);
			videoView.setVideoURI(video);
			videoView.requestFocus();
			mediaController.setMediaPlayer(videoView);
			videoView.setOnPreparedListener(new OnPreparedListener() {
				@Override
				public void onPrepared(MediaPlayer mp) {
					progressDialog.dismiss();
					videoView.start();
				}

			});

		} catch (Exception e) {
			progressDialog.dismiss();
			System.out.println("Video Play Error :" + e.toString());
			finish();
		}

	}

	@Override
	public void onDestroy() {
		super.onDestroy(); // Always call the superclass

	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	class MyTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			listview = (ListView) findViewById(R.id.PhoneVideoList);
			videoView = (VideoView) findViewById(R.id.viewvideo);

		}

		@Override
		protected Void doInBackground(Void... params) {
			try {
				parseHtml("http://192.168.84.148/media/");

				for(int i = 0;i<listvideoinfo.size();i++)
				{
					  Bitmap bmThumbnail = ThumbnailUtils.createVideoThumbnail(listvideoinfo.get(i).getPath(), Thumbnails.MICRO_KIND);
					  listvideoinfo.get(i).setBmThumbnail(bmThumbnail);
				}
			} catch (Exception e) {
				progressDialog.dismiss();
				finish();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);

			listview.setAdapter(new VideoAdapter(ListVideoActivity.this,
					R.layout.row, listvideoinfo));
			listview.setOnItemClickListener(videogridlistener);
			PlayVideo(listvideoinfo.get(0).getPath());
		}
	}

	private void parseHtml(String url) {
		Document doc;
		try {

			// need http protocol
			doc = Jsoup.connect(url).get();

			// get page title
			String title = doc.title();
			System.out.println("title : " + title);

			// get all links
			Elements links = doc.select("a[href]");
			System.out.println("size" + links.size());
			for (Element link : links) {

				// get the value from href attribute
				System.out.println("text : " + link.text());

				String result = link.text();
				if (result.endsWith("mp4")) {
					String name = result.substring(0, result.indexOf('.'));
					System.out.println("link : " + url + link.attr("href"));
					VideoInfo videoinfo = new VideoInfo(
							url + link.attr("href"), name);
					listvideoinfo.add(videoinfo);
				}

			}

			for (Element link : links) {

				// get the value from href attribute
				String result = link.text().trim();
				if (result.endsWith("txt")) {

					String info = result.substring(0, result.indexOf('.'));
					int length = listvideoinfo.size();
					for (int i = 0; i < length; i++) {
						if (listvideoinfo.get(i).getTitle().equals(info)) {
							StringBuilder text = new StringBuilder();

							try {
								String str = "";
								URL text_url = new URL(url + link.attr("href"));

								BufferedReader in = new BufferedReader(
										new InputStreamReader(
												text_url.openStream()));

								while ((str = in.readLine()) != null) {
									text.append(str);
								}
								in.close();
							} catch (MalformedURLException e1) {
							} catch (IOException e) {
							}

							listvideoinfo.get(i).setInfo(text.toString());
							break;
						}
					}
				}

			}


		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private OnItemClickListener videogridlistener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View v, int position,
				long id) {
			
			//PlayVideo(listvideoinfo.get(position).getPath());
			Intent intent = new Intent(ListVideoActivity.this, VideoActivity.class);
			intent.putExtra(VideoInfo.PATH_VIDEO, listvideoinfo.get(position).getPath());
			intent.putExtra(VideoInfo.INFO_VIDEO, listvideoinfo.get(position).getInfo());
			intent.putExtra(VideoInfo.TITLE_VIDEO, listvideoinfo.get(position).getTitle());
			
			startActivity(intent);

		}

	};

}
